package top.xchch.creational.prototype.version03;

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

import java.io.*;

public class DeepPrototype implements Serializable, Cloneable {
    public String name;
    public DeepCloneableTarget target;

    public DeepPrototype() {}

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public DeepCloneableTarget getTarget() {
        return target;
    }

    public void setTarget(DeepCloneableTarget target) {
        this.target = target;
    }

    /**
     * 1. 通过clone方法
     */
    @Override
    protected DeepPrototype clone() throws CloneNotSupportedException {
        DeepPrototype deepPrototype = (DeepPrototype) super.clone();
        deepPrototype.target = deepPrototype.target.clone();
        return deepPrototype;
    }

    /**
     * 通过对象的序列化实现(推荐)
     */
    public DeepPrototype deepClone() {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            // 序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepPrototype copyObject = (DeepPrototype)ois.readObject();
            return copyObject;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return null;
        }finally {
            try {
                bis.close();
                oos.close();
                bos.close();
                ois.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
